package org.jeecg.modules.mes.produce.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataBomitem;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataReplacematerial;
import org.jeecg.modules.mes.client.StockClient;
import org.jeecg.modules.mes.client.SystemClient;
import org.jeecg.modules.mes.client.TransactionClient;
import org.jeecg.modules.mes.order.entity.MesOrderProduce;
import org.jeecg.modules.mes.produce.entity.MesCommandbillInfo;
import org.jeecg.modules.mes.produce.entity.MesCommandbillPitem;
import org.jeecg.modules.mes.produce.service.IMesCommandbillInfoService;
import org.jeecg.modules.mes.produce.service.IMesCommandbillPitemService;
import org.jeecg.modules.mes.storage.entity.MesStorageWholesale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 制造中心—制令单BOM项目
 * @Author: jeecg-boot
 * @Date: 2020-12-17
 * @Version: V1.0
 */
@Api(tags = "制造中心—制令单BOM项目")
@RestController
@RequestMapping("/produce/mesCommandbillPitem")
@Slf4j
public class MesCommandbillPitemController extends JeecgController<MesCommandbillPitem, IMesCommandbillPitemService> {
    @Autowired
    private IMesCommandbillPitemService mesCommandbillPitemService;
    @Autowired
    private IMesCommandbillInfoService mesCommandbillInfoService;
    @Autowired
    private SystemClient systemClient;
    @Autowired
    private TransactionClient transactionClient;
    @Autowired
    private StockClient stockClient;

    /**
     * 分页列表查询
     *
     * @param mesCommandbillPitem
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "制造中心—制令单BOM项目-分页列表查询")
    @ApiOperation(value = "制造中心—制令单BOM项目-分页列表查询", notes = "制造中心—制令单BOM项目-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(MesCommandbillPitem mesCommandbillPitem,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        if(StringUtils.isNotBlank(mesCommandbillPitem.getWholid())){
            MesStorageWholesale wholesale = stockClient.findById(mesCommandbillPitem.getWholid());
            if (wholesale==null){
                return Result.error("未找到该二维码信息！");
            }
            if (StringUtils.isBlank(mesCommandbillPitem.getCommandbillId())){
                return Result.error("根据二维码查询需传入制令单commandbillId！");
            }
            MesCommandbillInfo info = mesCommandbillInfoService.getById(mesCommandbillPitem.getCommandbillId());
            if (info==null){
                return Result.error("根据二维码查询时未找到制令单信息！");
            }
            System.out.println(" wholesale:"+wholesale+" info:"+info);
            //检查是不是替代料，是的话根据主料号搜索
            List<MesChiefdataReplacematerial> replacematerials = systemClient.queryReplaceCode(info.getMechanismCode(),"",wholesale.getProductCode());
            if (replacematerials.size()>0){
                mesCommandbillPitem.setWholid(null);
                mesCommandbillPitem.setMaterielCode(replacematerials.get(0).getMainCode());
            }else{
                mesCommandbillPitem.setWholid(null);
                mesCommandbillPitem.setMaterielCode(wholesale.getProductCode());
            }
        }

        QueryWrapper<MesCommandbillPitem> queryWrapper = QueryGenerator.initQueryWrapper(mesCommandbillPitem, req.getParameterMap());
        Page<MesCommandbillPitem> page = new Page<MesCommandbillPitem>(pageNo, pageSize);
        IPage<MesCommandbillPitem> pageList = mesCommandbillPitemService.page(page, queryWrapper);

        for (int i = 0; i < pageList.getRecords().size(); i++) {
            MesCommandbillPitem commandbillPitem=pageList.getRecords().get(i);

            if(StringUtils.isBlank(commandbillPitem.getRealNum())) {
                MesOrderProduce produce = transactionClient.queryMesProduceById(commandbillPitem.getProorderId());
                BigDecimal grossNum = new BigDecimal(produce.getGrossAccount());//生产订单总数量
                BigDecimal requireNum = new BigDecimal(commandbillPitem.getRequireNum());//物料需求数量
                MesCommandbillInfo commandbillInfo = mesCommandbillInfoService.getById(commandbillPitem.getCommandbillId());
                BigDecimal planNUm = new BigDecimal(commandbillInfo.getPlantNum());//制令单计划数量
                BigDecimal number = requireNum.multiply(planNUm.divide(grossNum, 3, RoundingMode.HALF_UP));
                BigDecimal realNum = number.setScale(0, BigDecimal.ROUND_HALF_UP);//去掉小数位进一
                commandbillPitem.setRealNum(realNum.toString());
                pageList.getRecords().get(i).setRealNum(realNum.toString());
                mesCommandbillPitemService.updateById(commandbillPitem);
            }
            //根据bomitem获取客户料号
            if (StringUtils.isNotBlank(commandbillPitem.getMaterielCode())) {
                MesChiefdataBomitem materielCodeitem = systemClient.getMCodebomitemForIn(commandbillPitem.getMaterielCode().toString());
                if (materielCodeitem != null && StringUtils.isNotBlank(materielCodeitem.getClientCode())) {
                    pageList.getRecords().get(i).setClientCode(materielCodeitem.getClientCode());
                }
            }
        }
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param mesCommandbillPitem
     * @return
     */
    @AutoLog(value = "制造中心—制令单BOM项目-添加")
    @ApiOperation(value = "制造中心—制令单BOM项目-添加", notes = "制造中心—制令单BOM项目-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody MesCommandbillPitem mesCommandbillPitem) {
        mesCommandbillPitemService.save(mesCommandbillPitem);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mesCommandbillPitem
     * @return
     */
    @AutoLog(value = "制造中心—制令单BOM项目-编辑")
    @ApiOperation(value = "制造中心—制令单BOM项目-编辑", notes = "制造中心—制令单BOM项目-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody MesCommandbillPitem mesCommandbillPitem) {
        mesCommandbillPitemService.updateById(mesCommandbillPitem);
        return Result.ok("编辑成功!");
    }
    /**
     * 制令单批量转产
     * @return
     */
    @AutoLog(value = "制造中心—制令单BOM项目-制令单批量转产")
    @ApiOperation(value = "制造中心—制令单BOM项目-制令单批量转产", notes = "制造中心—制令单BOM项目-制令单批量转产  mobileType 转产编号 268 、mesCommandbillPitemList  原制令单信息 、newCode  需要转的制令单code")
    @PostMapping(value = "/wholeChangeProduce")
    public Result<?> wholeChangeProduce(@RequestBody MesCommandbillInfo info){
        if (StringUtils.isBlank(info.getMobileType())){
            return Result.error("编码不能为空！！！");
        }
        if (StringUtils.isBlank(info.getNewCode())){
            return Result.error("需要转的制令单编码不能为空！！！");
        }
        if (info.getMesCommandbillPitemList().size()==0){
            return Result.error("制令单bom不能为空！！！");
        }
        boolean mark=mesCommandbillPitemService.wholeChangeProduce(info.getMobileType(),info.getNewCode(),info.getMesCommandbillPitemList());
        if(mark) {
            return Result.ok("转产成功!");
        }else {
            return Result.error("转产失败！请检查！！！");
        }
    }

    /**
     * 远程调用，编辑指令单BOM
     *
     * @param mesCommandbillPitem
     * @return
     */
    @PutMapping(value = "/editComitem")
    public String editComitem(@RequestBody MesCommandbillPitem mesCommandbillPitem) {
        mesCommandbillPitemService.updateById(mesCommandbillPitem);
        return "编辑成功!";
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "制造中心—制令单BOM项目-通过id删除")
    @ApiOperation(value = "制造中心—制令单BOM项目-通过id删除", notes = "制造中心—制令单BOM项目-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        mesCommandbillPitemService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 远程调用，通过生产订单id删除制令单BOM
     *
     * @param orderId
     * @return
     */
    @DeleteMapping(value = "/deleteCommandBomByorderId")
    public String deleteCommandBomByorderId(@RequestParam(name = "orderId", required = true) String orderId) {
        QueryWrapper<MesCommandbillPitem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("proorder_id", orderId);
        mesCommandbillPitemService.remove(queryWrapper);
        return "删除成功!";
    }

    /**
     * 远程调用，通过生产订单id查询BOM详情
     *
     * @param proorderId 订单id
     * @return
     */
    @GetMapping(value = "/getCommandBomByorderId")
    public boolean getCommandBomByorderId(@RequestParam("proorderId") String proorderId) {
        LambdaQueryWrapper<MesCommandbillPitem> wrapper = new LambdaQueryWrapper();
        wrapper.eq(MesCommandbillPitem::getProorderId, proorderId);
        List<MesCommandbillPitem> items = mesCommandbillPitemService.list(wrapper);
        for (MesCommandbillPitem item : items) {
            if (Strings.isNotBlank(item.getDeliveryNum()) && Long.parseLong(item.getDeliveryNum()) > 0) {
                return false;
            }
        }
        return true;
    }


    /**
     * 远程调用，通过制令单id查询制令单BOM，判断是否大于等于已发数量，大于则发料完成
     *
     * @param commandbillId
     * @return
     */
    @GetMapping(value = "/getCommandBomBycommandbillId")
    public String getCommandBomBycommandbillId(@RequestParam(name = "commandbillId", required = true) String commandbillId,@RequestParam(name = "materielCode", required = false) String materielCode) {
        //获取制令单主表数据
        MesCommandbillInfo mescbinfo = mesCommandbillInfoService.getById(commandbillId);
        String msg = "";
        if ("未完成".equals(mescbinfo.getDeliveryState())) {
            //查询发料数量为0的有多少，数量为0则发料完成
            QueryWrapper<MesCommandbillPitem> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("commandbill_id", commandbillId);
            queryWrapper1.eq("if_delivery", "未发料");
            List<MesCommandbillPitem> mesCommandbillPitemList1 = mesCommandbillPitemService.list(queryWrapper1);
            if (mesCommandbillPitemList1.size() == 0) {
                MesCommandbillInfo mesCommandbillInfo = new MesCommandbillInfo();
                mesCommandbillInfo.setId(commandbillId);
                mesCommandbillInfo.setDeliveryState("已完成");
                mesCommandbillInfoService.updateById(mesCommandbillInfo);
                msg = "发料已完成";
            } else {
                msg = "发料未完成";
            }
        }
        if ("未完成".equals(mescbinfo.getGlazeState())) {
            //查询上料数量为0的有多少，数量为0则制令单发料完成
            QueryWrapper<MesCommandbillPitem> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("commandbill_id", commandbillId);
            queryWrapper2.eq("if_Glaze", "未上料");
            List<MesCommandbillPitem> mesCommandbillPitemList2 = mesCommandbillPitemService.list(queryWrapper2);
            if (mesCommandbillPitemList2.size() == 0) {
                MesCommandbillInfo mesCommandbillInfo = new MesCommandbillInfo();
                mesCommandbillInfo.setId(commandbillId);
                mesCommandbillInfo.setGlazeState("已完成");
                mesCommandbillInfoService.updateById(mesCommandbillInfo);
                msg = "上料已完成";
            } else {
                msg = "上料未完成";
            }
        }

        //判断制令单item数量
        QueryWrapper<MesCommandbillPitem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("commandbill_id", commandbillId);
        if (StringUtils.isNotBlank(materielCode)) {
            queryWrapper.eq("materiel_code", materielCode);
        }
        List<MesCommandbillPitem> mesCommandbillPitemList = mesCommandbillPitemService.list(queryWrapper);

        for (MesCommandbillPitem mescpit : mesCommandbillPitemList) {
            //需要数量  返回值 -1 小于 0 等于 1 大于
            BigDecimal realNum = new BigDecimal(mescpit.getRealNum());
            //判断发料没有
            if ("未发料".equals(mescpit.getIfDelivery())) {
                //已发料数量
                BigDecimal DeliveryNum = new BigDecimal(mescpit.getDeliveryNum());
                //需要的数量大于等于发料数量则发料已完成
                if (DeliveryNum.compareTo(realNum) == 0 || DeliveryNum.compareTo(realNum) == 1) {
                    MesCommandbillPitem item = new MesCommandbillPitem();
                    item.setId(mescpit.getId());
                    item.setIfDelivery("已发料");
                    mesCommandbillPitemService.updateById(item);
                }
            }
            //判断上料没有
            if ("未上料".equals(mescpit.getIfGlaze())) {
                //已上料数量
                BigDecimal UnglazeNum = new BigDecimal(mescpit.getUnglazeNum());
                //需要的数量大于等于发料数量则发料已完成
                if (UnglazeNum.compareTo(realNum) == 0 || UnglazeNum.compareTo(realNum) == 1) {
                    MesCommandbillPitem item = new MesCommandbillPitem();
                    item.setId(mescpit.getId());
                    item.setIfGlaze("已上料");
                    mesCommandbillPitemService.updateById(item);
                }
            }
        }
        return msg;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "制造中心—制令单BOM项目-批量删除")
    @ApiOperation(value = "制造中心—制令单BOM项目-批量删除", notes = "制造中心—制令单BOM项目-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mesCommandbillPitemService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "制造中心—制令单BOM项目-通过id查询")
    @ApiOperation(value = "制造中心—制令单BOM项目-通过id查询", notes = "制造中心—制令单BOM项目-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        MesCommandbillPitem mesCommandbillPitem = mesCommandbillPitemService.getById(id);
        if (mesCommandbillPitem == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(mesCommandbillPitem);
    }

    /**
     * 远程调用，通过id获取制令单BOM的数据
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryPitemById")
    public MesCommandbillPitem queryPitemById(@RequestParam(name = "id", required = true) String id) {
        MesCommandbillPitem mesCommandbillPitem = mesCommandbillPitemService.getById(id);
        return mesCommandbillPitem;
    }

    /**
     * 远程调用，通过子表id获取制令单BOM主表的数据
     *
     * @param itemId
     * @return
     */
    @GetMapping(value = "/queryCommandbillByItemId")
    public MesCommandbillInfo queryCommandbillByItemId(@RequestParam(name = "itemId", required = true) String itemId) {
        MesCommandbillPitem mesCommandbillPitem = mesCommandbillPitemService.getById(itemId);
        if(mesCommandbillPitem!=null){
            return mesCommandbillInfoService.getById(mesCommandbillPitem.getCommandbillId());
        }
        return new MesCommandbillInfo();
    }

    /**
     * 远程调用，通过制令单号和料号，获取制令单BOM的数据
     *
     * @param commandCode
     * @param mCode
     * @return
     */
    @GetMapping(value = "/getPitemByCode")
    public MesCommandbillPitem getPitemByCode(@RequestParam(name = "commandCode", required = true) String commandCode,
                                              @RequestParam(name = "mCode", required = true) String mCode) {
        QueryWrapper<MesCommandbillPitem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("commandbill_code", commandCode).eq("materiel_code", mCode);
        MesCommandbillPitem mesCommandbillPitem = mesCommandbillPitemService.getOne(queryWrapper);
        return mesCommandbillPitem;
    }
    /**
     * 远程调用，通过制令单id和料号，获取制令单BOM的数据
     *
     * @param commandId
     * @param mCode
     * @return
     */
    @GetMapping(value = "/getPitemById")
    public MesCommandbillPitem getPitemById(@RequestParam(name = "commandId", required = true) String commandId,
                                              @RequestParam(name = "mCode", required = true) String mCode) {
        QueryWrapper<MesCommandbillPitem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("commandbill_id", commandId).eq("materiel_code", mCode);
        MesCommandbillPitem mesCommandbillPitem = mesCommandbillPitemService.getOne(queryWrapper);
        return mesCommandbillPitem;
    }

    /**
     * 根据制令单ID和物料类型查询制令单子数据
     */
    @GetMapping(value = "/getItemByCommandIdAndType")
    public MesCommandbillPitem getItemByCommandIdAndType(@RequestParam(name = "commandId") String commandId,
                                                         @RequestParam(name = "materiel_type") String materiel_type) {
        QueryWrapper<MesCommandbillPitem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("commandbill_id", commandId).eq("materiel_type", materiel_type);
        MesCommandbillPitem mesCommandbillPitem = mesCommandbillPitemService.getOne(queryWrapper);
        return mesCommandbillPitem;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mesCommandbillPitem
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MesCommandbillPitem mesCommandbillPitem) {
        return super.exportXls(request, mesCommandbillPitem, MesCommandbillPitem.class, "制造中心—制令单BOM项目");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MesCommandbillPitem.class);
    }

}
